package com.kkb.controller;

import com.kkb.util.HttpUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/v1/data.js")
public class DataJSServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. 设定编码
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/json;charset=utf-8");

        //2. 加载网络数据
        String result = null;
        try {
            result = HttpUtil.get("http://kkb.zaixianke.com/v1/data");

        } catch (Exception e) {
            e.printStackTrace();
        }
        //3. 将JSON格式的数据，按照规则配置为JS文件。
        //规则是： 在JS文件中，创建一个常量VIDEOS，常量的值是上面读取的JSON数据text
        //4. 将读取到的result，返回给前端index.html
        response.getWriter().append("const VIDEOS = ").append(result).append(";");


    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }


}
